﻿using System;
using System.Collections.Generic;
using System.Text;
using MessagePack;
using Newtonsoft.Json;

namespace Chat
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TClass"></typeparam>
    public class ClassFormater<TClass> : MessagePack.Formatters.IMessagePackFormatter<TClass>
    {
        /// <summary>
        /// 二进制反序列化
        /// </summary>
        /// <param name="bytes">一个未知大小的空间</param>
        /// <param name="offset">当前已经读到哪里了</param>
        /// <param name="formatterResolver">一个格式化管道</param>
        /// <param name="readSize">读取了多少字节</param>
        /// <returns></returns>
        public TClass Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if(MessagePackBinary.IsNil(bytes,offset))
            {
                readSize = 1;
                return default(TClass);
            }
            var formatter = formatterResolver.GetFormatterWithVerify<String>();
            string json= MessagePackBinary.ReadString(bytes, offset, out readSize);
            offset += readSize;
            return JsonConvert.DeserializeObject<TClass>(json);
        }

        /// <summary>
        /// 二进制序列化
        /// </summary>
        /// <param name="bytes">一个65535大小的空间</param>
        /// <param name="offset">传入0</param>
        /// <param name="value">待序列化的数据</param>
        /// <param name="formatterResolver">一个格式化管道</param>
        /// <returns>序列化后数据长度</returns>
        public int Serialize(ref byte[] bytes, int offset, TClass value, IFormatterResolver formatterResolver)
        {
            if(value==null)
            {
                return MessagePackBinary.WriteNil(ref bytes, offset);
            }
            string json = JsonConvert.SerializeObject(value);
            var formater = formatterResolver.GetFormatterWithVerify<string>();
            return formater.Serialize(ref bytes, offset, json, formatterResolver);
        }
    }
}
